var path=require('path');
var bodyParser=require('body-parser');
var express=require('express');
var session=require('express-session');
var flash=require('connect-flash');
var exHbs=require('express-handlebars').create({
    defaultLayout:'main',
    extname:'.hbs',
    helpers:{
        section: function (name, opts) {
            if(!this._sections)this._sections={};
            this._sections[name]=opts.fn(this);
            return null;
        }
    }
});
var config=require('./config/defaults.js')
var app=express();


//settings
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.engine('hbs',exHbs.engine);
app.set('port',config.port);

//middleware
app.use(express.static(__dirname+'/public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session(config.session));
app.use(flash());


//router
app.use('/',require('./routes/home'));
app.use('/add',require('./routes/add'));
app.use('/edit',require('./routes/edit'));
app.use('/mock',require('./routes/mock'));

//404
app.use((req,res)=>{
    res.sendStatus(404);
});

//error
app.use((err,req,res,next)=>{
    console.error('\nAPP Error:');
    console.log(err);
    res.sendStatus(500);
});

module.exports=app;